package com.atguigu.srb.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.util.RandomUtils;
import com.atguigu.srb.common.util.RegexValidateUtils;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.util.SmsProperties;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void sendCode(String mobile) {
        // 校验手机号码
        boolean b = RegexValidateUtils.checkCellphone(mobile);
        Assert.isTrue(b, ResponseEnum.MOBILE_ERROR);

        // 生成验证码
        String fourBitRandom = RandomUtils.getFourBitRandom();

        // 调用阿里云api
        // 公共参数
        DefaultProfile defaultProfile = DefaultProfile.getProfile(SmsProperties.REGION_ID,SmsProperties.KEY_ID,SmsProperties.KEY_SECRET);

        // 请求客户端
        IAcsClient iAcsClient = new DefaultAcsClient(defaultProfile);

        // 请求参数
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setSysMethod(MethodType.POST);
        commonRequest.setSysDomain("dysmsapi.aliyuncs.com");
        commonRequest.setSysAction("SendSms");
        commonRequest.setSysVersion("2017-05-25");

        commonRequest.putQueryParameter("PhoneNumbers",mobile);
        commonRequest.putQueryParameter("SignName",SmsProperties.SIGN_NAME);
        commonRequest.putQueryParameter("TemplateCode",SmsProperties.TEMPLATE_CODE);
        Map<String,String> map = new HashMap<>();
        map.put("code",fourBitRandom);
        commonRequest.putQueryParameter("TemplateParam", JSON.toJSONString(map));

        // 发送请求，返回结果
        CommonResponse commonResponse = null;
        try {
            commonResponse = iAcsClient.getCommonResponse(commonRequest);
        }catch (ClientException e){
            e.printStackTrace();
        }

        System.out.println(commonResponse);

        // 发送给redis
        String data = commonResponse.getData();
        Gson gson = new Gson();
        HashMap<String,String> resultMap = gson.fromJson(data,HashMap.class);
        String commonResponseCode = resultMap.get("Code");
        Assert.isTrue((null!=commonResponseCode)&&(commonResponseCode.equals("OK")),ResponseEnum.ERROR);
        redisTemplate.opsForValue().set("srb:sms:code:" + mobile,fourBitRandom);
    }
}